<?php
/**
 * Created by <xinxin.deng>.
 * Author: xinxin.deng
 * Date: 2018/3/13 10:19
 */

//error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_model.message.message_explain");
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_core.m_pinyin");
\ns_core\m_load::load_old("nn_logic/log_model/nn_log.class.php");
\ns_core\m_load::load_old("nn_logic/video/vod_index.class.php");
\ns_core\m_load::load_old("nn_logic/video/vod_media.class.php");
//\ns_core\m_load::load_old("nn_logic/video/vod.class.php");
\ns_core\m_load::load_np("np_http_curl.class.php");
$arr_dir = explode('|', str_replace(array ('/','\\'), '|', __DIR__));
$str_dir = array_pop($arr_dir);
define('DEFAULT_SOURCE_ID', $str_dir);

class message extends \ns_model\message\message_explain
{
    private $view_type = array(
        '0' => array('84','112','6','9','32','14','28','31'),//电影
        '1' => array('5','83','34'),//电视剧
        '2' => array('19','87'),//综艺
        '3' => array('20','88'),//动漫
        '4' => array('18','86'),//音乐
        '5' => array('17','85'),//纪实
        '6' => array('22','97'),//教育
        '7' => array('23','98'),//体育
        '8' => array('25','100'),//生活
        '9' => array('24','99'),//财经
        '10' => array('26','101','10'),//微电影
        '11' => array('27','102'),//品牌专区
        '12' => array('21','92','33','113'),//广告
        '13' => array('11','30'),//新闻
    );//影片种类

    private $msg_id = '';
    private $source_id = '';
    private $arr_cp_config = array();

    private $asset_id = '';
    private $index_id = '';
    private $media_id = '';
    private $type = '';

    /**
     * 消息解析
     * @param $message
     * @return array|multitype
     */
    public function explain($message)
    {
        \ns_core\m_load::load_np("np_xml_to_array.class.php");
        $this->type = '';
        $this->asset_id = '';
        $this->index_id = '';
        $this->media_id = '';

        $this->msg_id = $message['nns_message_id'];
        $this->source_id = $message['nns_cp_id'];
        $this->arr_cp_config = \m_config::_get_cp_info($message['nns_cp_id']);
        //本地获取数据
        $content = $this->get_message_content($message);
        if($content['ret'] != 0 || strlen($content['data_info']) < 1)
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败，消息ID[{$message['nns_message_id']}]" . $content['reason']);
            return $content;
        }
        $str_content = \m_config::trim_xml_header($content['data_info']);
        if(!\m_config::is_xml($str_content))
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败,消息ID[{$message['nns_message_id']}]xml内容非xml结构");
            return \m_config::return_data(NS_CDS_FAIL,"消息ID[{$message['nns_message_id']}]xml内容非xml结构");
        }
        //解析下载的XML
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($str_content);
        $xml = $dom->saveXML();
        $xml_arr = np_xml_to_array::parse2($xml);
        if(!is_array($xml_arr) || empty($xml_arr))
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败,消息ID[{$message['nns_message_id']}]xml解析失败");
            return \m_config::return_data(NS_CDS_FAIL,"消息ID[{$message['nns_message_id']}]xml解析失败");
        }

        if(!isset($xml_arr['content']) || empty($xml_arr['content']))
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败,消息ID[{$message['nns_message_id']}],解析得到的媒资元数据错误");
            return \m_config::return_data(1, "解析得到的媒资元数据错误");
        }

        $this->type = (int)$xml_arr['assetdesc'];
        switch ($xml_arr['assettype'])
        {
            case 1 ://点播业务处理
                if ($xml_arr['assetdesc'] == 1) //主媒资
                {
                    //全局消息自带反馈主媒资id
                    $this->asset_id = $xml_arr['content']['assetid'];

                    $re = $this->video_execute($xml_arr);
                }
                elseif ($xml_arr['assetdesc'] == 2) //分集
                {
                    //全局消息自带反馈主媒资id
                    $this->asset_id = $xml_arr['content']['assetid'];
                    //全局消息自带反馈分集id
                    $this->index_id = $xml_arr['content']['partid'];
                    $re = $this->index_execute($xml_arr);
                }
                elseif ($xml_arr['assetdesc'] == 3) //片源
                {
                    //全局消息自带反馈主媒资id
                    $this->asset_id = $xml_arr['content']['videos']['file']['assetid'];
                    //全局消息自带反馈分集id
                    $this->index_id = $xml_arr['content']['videos']['file']['partid'];
                    //全局消息自带反馈片源id
                    $this->media_id = $xml_arr['content']['videos']['file']['fileid'];
                    $re = $this->media_execute($xml_arr);
                }
                elseif ($xml_arr['assetdesc'] == 11)//融合媒资
                {
                    $re = $this->fuse_execute($xml);
                }
                elseif ($xml_arr['assetdesc'] == 98)
                {
                    $re = $this->add_category_execute($xml_arr);
                }
                break;
            //直播业务
            case 2 :
                if ($xml_arr['assetdesc'] == 96)
                {
                    $re = $this->live_channel_lock_execute($xml_arr);
                }
                elseif($xml_arr['assetdesc'] == 97)
                {
                    $re = $this->playbill_execute($xml_arr);
                }
                break;
            default:
                $re = \m_config::return_data(1, "不支持的工单类型");
                break;
        }

        if ($re['ret'] != 0)
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_FAIL, "消息接收成功,注入失败,消息ID[{$message['nns_message_id']}],原因" . $re['reason']);
        }
        else
        {
            $this->create_xml_respond_msg_to_csp(NS_CDS_SUCCE, "消息接收成功,等待注入,消息ID[{$message['nns_message_id']}]");
        }
        unset($this->type);
        unset($this->asset_id);
        unset($this->index_id);
        unset($this->media_id);
        return $re;
    }

    /**
     * 主媒资队列注入
     * @param $data
     * @return array|multitype|void
     */
    private function video_execute($data)
    {
        $content = $data['content'];
        switch ($data['assetoperation'])
        {
            // 添加
            case 1:
                //获取view_type
                $view_type = '0';
                foreach ($this->view_type as $key=>$value)
                {
                    if(in_array($content['fstlvlid'], $value))
                    {
                        $view_type = $key;
                        break;
                    }
                }

                $asset_category = (isset($content['fstname']) && strlen($content['fstname']) >0) ? $content['fstname'] : '电影';
                $do_category = array(
                    'base_info' => array(
                        'nns_name' => $asset_category,   //栏目名称支持多层目录，多层目录的时候 /分割
                        'nns_import_category_id' => '', //栏目名称支持多层目录，多层目录的时候 /分割
                        'nns_cp_id' => $this->source_id,
                        'nns_import_parent_category_id' => '',
                        'nns_video_type' => '0',  //媒资类型  0 点播 | 1 直播
                    ),
                );
                //创建栏目
                $result = $this->category_action('add', $do_category);
                if($result['ret'] != 0)
                {
                    return $result;
                }
                if(!isset($result['data_info']['base_info']['nns_id']) || strlen($result['data_info']['base_info']['nns_id']) <1)
                {
                    return m_config::return_data(1,'创建栏目失败');
                }
                $nns_category_id = $result['data_info']['base_info']['nns_id'];

                //导演信息
                $director='';
                $directornew='';
                if(is_array($content['directors']) && !empty($content['directors']))
                {
                    if(array_key_exists('key',$content['directors']['director']))
                    {
                        $director = $content['directors']['director']['value'];
                        $directornew = $content['directors']['director']['value'].'|'.$content['directors']['director']['key'];
                    }
                    else
                    {
                        foreach ($content['directors']['director'] as $key=>$value)
                        {

                            $director.=$value['value'].',';
                            $directornew.=$value['value'].'|'.$value['key'].';';
                        }
                        $director=rtrim($director, ",");
                        $directornew=rtrim($directornew, ";");
                    }
                }
                else
                {
                    $director = $content['director'];
                }
                //演员信息
                $leader='';
                $leadernew='';
                if(is_array($content['leaders']))
                {
                    if(array_key_exists('key',$content['leaders']['leader']))
                    {
                        $leader = $content['leaders']['leader']['value'];
                        $leadernew = $content['leaders']['leader']['value'].'|'.$content['leaders']['leader']['key'];
                    }
                    else
                    {
                        foreach ($content['leaders']['leader'] as $key=>$value)
                        {
                            $leader.=$value['value'].',';
                            $leadernew.=$value['value'].'|'.$value['key'].';';
                        }
                        $leader=rtrim($leader, ",");
                        $leadernew=rtrim($leadernew, ";");
                    }
                }
                else
                {
                    $leader = $content['leader'];
                }
                $adaptor='';
                $adaptornew='';
                if(is_array($content['adaptors']))
                {
                    if(array_key_exists('key',$content['adaptors']['adaptor']))
                    {
                        $adaptor = $content['adaptors']['adaptor']['value'];
                        $adaptornew = $content['adaptors']['adaptor']['value'].'|'.$content['adaptors']['adaptor']['key'];
                    }
                    else
                    {
                        foreach ($content['adaptors']['adaptor'] as $key=>$value)
                        {
                            $adaptor.=$value['value'].',';
                            $adaptornew.=$value['value'].'|'.$value['key'].';';
                        }
                        $adaptor=rtrim($adaptor, ",");
                        $adaptornew=rtrim($adaptornew, ";");
                    }
                }
                else
                {
                    $adaptor = $content['adaptor'];
                }
                //若simplespell为多个多音
                if(!empty($content['simplespell']))
                {
                    $simplespell = $content['simplespell'];
                    if(strstr($simplespell,'|'))
                    {
                        $pinying = explode('|', $content['simplespell']);
                        $simplespell = $pinying[0];
                    }
                }
                else
                {
                    $simplespell = m_pinyin::get_pinyin_letter($content['clipname']);
                }
                //海报信息
                $temp_image=array();
                $image = $content['images']['image'];
                if (is_array($image) && !empty($image))
                {
                    if (array_key_exists('1', $image))
                    {
                        foreach ($image as $value)
                        {
                            if(array_key_exists($value['imgtype'], $temp_image))
                            {
                                continue;
                            }
                            // 1-横图 2-竖图、小图 3-方图
                            $temp_image[$value['imgtype']] = $value['filename'];
                        }
                    }
                    elseif (array_key_exists('filename', $image))
                    {
                        $temp_image[$image['imgtype']] = $image['filename'];
                    }
                }

                $add_series = array(
                    'base_info' => array(
                        'nns_name' => $content['clipname'],
                        'nns_view_type' => $view_type,
                        'nns_org_type' => '0',
                        'nns_tag' => '26,',
                        'nns_director' => $director,
                        'nns_actor' => $leader,
                        'nns_show_time' => $content['relasetime'],
                        'nns_view_len' => $content['duration'],
                        'nns_all_index' => intval($content['serialcount']),
                        'nns_new_index' => 0,
                        'nns_area' => $content['area'],
                        'nns_image0' => '',
                        'nns_image1' => '',
                        'nns_image2' => isset($temp_image[2]) ? $temp_image[2] : '',
                        'nns_image3' => '',
                        'nns_image4' => '',
                        'nns_image5' => '',
                        'nns_summary' => $content['story'],
                        'nns_remark' => '',
                        'nns_category_id' => $nns_category_id,
                        'nns_play_count' => '0',
                        'nns_score_total' => floatval($content['scores']),//评分
                        'nns_score_count' => '0',
                        'nns_point' => '0',
                        'nns_copyright_date' => $content['year'],
                        'nns_asset_import_id' => $content['originalid'],
                        'nns_pinyin' => $simplespell,
                        'nns_pinyin_length' => strlen($simplespell),
                        'nns_alias_name' => isset($content['othernme']) ? $content['othernme'] : '',
                        'nns_eng_name' => '',
                        'nns_language' => $content['language'],
                        'nns_text_lang' => '',
                        'nns_producer' => isset($data['info']['contentprovider']) ? $data['info']['contentprovider'] : '',
                        'nns_screenwriter' => $adaptor,
                        'nns_play_role' => '',
                        'nns_copyright_range' => '',
                        'nns_vod_part' => '',
                        'nns_keyword' => $content['keyword'],
                        'nns_import_source' => evn::get("project"),
                        'nns_kind' => $content['kind'],
                        'nns_copyright' => '',
                        'nns_clarity' => '',
                        'nns_image_v' => isset($temp_image[2]) ? $temp_image[2] : '',
                        'nns_image_s' => isset($temp_image[3]) ? $temp_image[3] : '',
                        'nns_image_h' => isset($temp_image[1]) ? $temp_image[1] : '',
                        'nns_cp_id' => $this->source_id,
                        'nns_conf_info' => '',
                        'nns_ext_url' => '',
                        'nns_ishuaxu' => isset($content['ishuaxu']) ? (int)$content['ishuaxu'] : 0,
                        'nns_positiveoriginalid' => isset($content['positiveoriginalid']) ? $content['positiveoriginalid'] : '',
                    ), //基本信息（存储于nns_vod表中）
                    'ex_info' => array(
                        'svc_item_id' => '',
                        'month_clicks' => '',
                        'week_clicks' => '',
                        'base_id' => '',
                        'asset_path' => '',
                        'ex_tag' => '',
                        'full_spell' => '',
                        'awards' => '',
                        'year' => $content['year'],
                        'play_time' => '',
                        'channel' => '',
                        'first_spell' => '',
                        'directornew' => $directornew,
                        'playernew' => $leadernew,
                        'adaptornew' => $adaptornew,
                    ), //扩展信息（存储于nns_vod_ex表中）
                );
                $result = $this->vod_action('add', $add_series);
                break;
            //删除
            case 2:
                //全局消息自带反馈主媒资id
                $this->asset_id = $content['id'];
                $delete_params = array(
                    'base_info' => array(
                        'nns_cp_id' => $this->source_id,
                        'nns_asset_import_id' => $content['originalid'],
                        'nns_import_source' => evn::get("project"),
                    ),
                );
                $result = $this->vod_action('delete', $delete_params);
                break;
        }

        return $result;
    }

    /**
     * 分集队列注入
     * @param $data
     * @return array|multitype
     */
    private function index_execute($data)
    {
        $content = $data['content'];

        switch ($data['assetoperation'])
        {
            case '1':
                $clip_index = (intval($content['serialno']) >= 1) ? intval($content['serialno']) : 1;
                if(empty($content['awards']) || !isset($content['awards']))
                {
                    $content['awards'] = $content['story'];
                }
                //导演信息
                $director='';
                $directornew='';
                if(is_array($content['directors']) && !empty($content['directors']))
                {
                    foreach ($content['directors'] as $key => $value)
                    {
                        $director .= $value['value'] . ',';
                        $directornew .= $value['value'] . '|' . $value['key'] . ';';
                    }
                    $director = rtrim($director, ",");
                    $directornew = rtrim($directornew, ";");

                }
                //演员信息
                $leader='';
                $leadernew='';
                if(is_array($content['leaders']))
                {
                    foreach ($content['leaders'] as $key => $value)
                    {
                        $leader .= $value['value'] . ',';
                        $leadernew .= $value['value'] . '|' . $value['key'] . ';';
                    }
                    $leader = rtrim($leader, ",");
                    $leadernew = rtrim($leadernew, ";");
                }
                $adaptor='';
                $adaptornew='';
                if(is_array($content['adaptors']))
                {
                    foreach ($content['adaptors'] as $key => $value)
                    {
                        $adaptor .= $value['value'] . ',';
                        $adaptornew .= $value['value'] . '|' . $value['key'] . ';';
                    }
                    $adaptor = rtrim($adaptor, ",");
                    $adaptornew = rtrim($adaptornew, ";");
                }
                $add_index = array(
                    'base_info' => array(
                        'nns_name' => $content['partname'],
                        'nns_index' => $clip_index - 1,
                        'nns_time_len' => $content['duration'],
                        'nns_summary' => $content['story'],
                        'nns_image' =>  $content['images']['image']['filename'],
                        'nns_play_count' => 0,
                        'nns_score_total' => 0,
                        'nns_score_count' => 0,
                        'nns_video_import_id' => $content['oriassetid'],
                        'nns_import_id' => $content['originalid'],
                        'nns_import_source' => evn::get("project"),
                        'nns_director' => $director,
                        'nns_actor' => $leader,
                        'nns_release_time' => $content['relasetime'],
                        'nns_update_time' => $content['updatetime'],
                        'nns_watch_focus' => addslashes($content['awards']),
                        'nns_cp_id' => $this->source_id,
                        'nns_conf_info' => '',
                        'nns_ext_url' => '',
                    ),
                    'ex_info' => array(
                        'isintact' => $content['isintact'],
                        'subordinate_name' => '',
                        'initials' => '',
                        'publisher' => '',
                        'first_spell' => '',
                        'caption_language' => '',
                        'language' => '',
                        'region' => '',
                        'adaptor' => '',
                        'sreach_key' => '',
                        'event_tag' => '',
                        'year' => '',
                        'sort_name' => '',
                        'directornew' => $directornew,
                        'playernew' => $leadernew,
                        'adaptornew' => $adaptornew,
                    ),
                );

                //分集注入
                $re = $this->index_action('add', $add_index);
                if($re['ret'] != 0)
                {
                    return $re;
                }
                $seekpoints = $content['seekpoints']['item'];
                //打点信息注入
                if(!empty($seekpoints))
                {
                    if (array_key_exists('1', $seekpoints))
                    {
                        foreach ($seekpoints as $item)
                        {

                        }
                    }
                    elseif (array_key_exists('@attributes', $seekpoints))
                    {

                    }
                }

                break;
            case '2':
                //全局消息自带反馈分集id
                $this->index_id = $content['id'];
                $delete_params = array(
                    'base_info' => array(
                        'nns_cp_id' => $this->source_id,
                        'nns_import_id' => $content['originalid'],
                        'nns_import_source' => evn::get("project"),
                    ),
                );
                $re = $this->index_action('delete', $delete_params);
                break;
        }
        return $re;
    }

    /**
     * 片源队列注入
     * @param $data
     * @return array|multitype
     */
    private function media_execute($data)
    {
        $content = $data['content'];

        switch ($data['assetoperation'])
        {
            case '1':
                $files = $content['videos']['file'];
                if(!is_array($files))
                {
                    return \m_config::return_data();
                }
                $info = array();
                if (is_array($files) && !empty($files))
                {
                    if (array_key_exists('fileid', $files))
                    {
                        $file = array(
                            'file_id' => $files['originalid'],
                            'file_type' => end(explode(".",$files['fileformat'])),
                            'file_name' => '',
                            'file_path' => $files['filename'],
                            'file_definition' => $this->_re_convert_media_type($files['fileformatdesc']),
                            'file_resolution' => $files['vga'],
                            'file_bit_rate' => $files['filebitrate'],
                            'file_time_len' => $files['fileduration'],
                            'FrameRate' => intval($files['framerate']),
                            'file_hash' => $files['filehash'],
                            'video_import_id' => $files['oriassetid'],
                            'index_import_id' => $files['oripartid'],
                            'media_import_id' => $files['originalid']
                        );
                        $file_size = round($files['filesize']/1024/1024);
                        $file_size = $file_size <= 0 ? 1 : $file_size;
                        $file['file_size'] = $file_size;
                        if(empty($files['vga']) && !empty($files['videowidth']) && !empty($files['videoheight']))
                        {
                            $file['file_resolution'] = $files['videowidth'] . '*' . $files['videoheight'];
                        }
                        $info = array($file);
                    }
                    elseif(array_key_exists('1', $files))
                    {
                        foreach ($files as $f_val)
                        {
                            $file = array(
                                'file_id' => $f_val['originalid'],
                                'file_type' => end(explode(".",$f_val['fileformat'])),
                                'file_name' => '',
                                'file_path' => $f_val['filename'],
                                'file_definition' => $this->_re_convert_media_type($f_val['fileformatdesc']),
                                'file_resolution' => $f_val['vga'],
                                'file_bit_rate' => $f_val['filebitrate'],
                                'file_time_len' => $f_val['fileduration'],
                                'FrameRate' => intval($f_val['framerate']),
                                'file_hash' => $f_val['filehash'],
                                'video_import_id' => $files['oriassetid'],
                                'index_import_id' => $files['oripartid'],
                                'media_import_id' => $files['originalid']
                            );
                            $file_size = round($f_val['filesize']/1024/1024);
                            $file_size = $file_size <= 0 ? 1 : $file_size;
                            $file['file_size'] = $file_size;
                            if(empty($f_val['vga']) && !empty($f_val['videowidth']) && !empty($f_val['videoheight']))
                            {
                                $file['file_resolution'] = $f_val['videowidth'] . '*' . $f_val['videoheight'];
                            }
                            $info[] = $file;
                        }
                    }
                }
                foreach ($info as $avl_movie)
                {
                    $add_media = array(
                        'base_info' => array(
                            'nns_name' => '',
                            'nns_type' => 1,
                            'nns_url' => $avl_movie['file_path'],
                            'nns_tag' => '26,',
                            'nns_mode' => $avl_movie['file_definition'],
                            'nns_kbps' => $avl_movie['file_bit_rate'],
                            'nns_content_id ' => '',
                            'nns_content_state' => 0,
                            'nns_filetype' => $avl_movie['file_type'],
                            'nns_play_count' => '0',
                            'nns_score_total' => '0',
                            'nns_score_count' => '0',
                            'nns_video_import_id' => $avl_movie['video_import_id'],
                            'nns_index_import_id' => $avl_movie['index_import_id'],
                            'nns_import_id' => $avl_movie['media_import_id'],
                            'nns_import_source' => evn::get("project"),
                            'nns_dimensions' => '0',
                            'nns_ext_url' => '',
                            'nns_file_size' => $avl_movie['file_size'],
                            'nns_file_time_len' => $avl_movie['file_time_len'],
                            'nns_file_frame_rate' => $avl_movie['FrameRate'],
                            'nns_file_resolution' => $avl_movie['file_resolution'],
                            'nns_cp_id' => $this->source_id,
                            'nns_ext_info' => '',
                            'nns_drm_enabled' => 0,
                            'nns_drm_encrypt_solution' => '',
                            'nns_drm_ext_info' => '',
                            'nns_domain' => 0,
                            'nns_media_type' => 1,
                            'nns_original_live_id' => '',
                            'nns_start_time' => '',
                            'nns_media_service' => 'HTTP',
                            'nns_conf_info' => '',
                            'nns_encode_flag' => 0,
                            'nns_live_to_media' => '',
                            'nns_media_service_type' => '',
                        ),
                        'ex_info' => array(
                            'file_hash' => '',
                            'file_width' => '',
                            'file_height' => '',
                            'file_scale' => '',
                            'file_coding' => '',
                        ),
                    );
                    $re = $this->media_action('add', $add_media);
                }
                break;
            case '2':
                //全局消息自带反馈片源id
                $this->media_id = $content['id'];
                $delete_params = array(
                    'base_info' => array(
                        'nns_cp_id' => $this->source_id,
                        'nns_import_id' => $content['originalid'],
                        'nns_import_source' => evn::get("project"),
                    ),
                );
                $re = $this->media_action('delete', $delete_params);
                break;
        }
        return $re;
    }

    /**
     * 映射片源清晰度
     * @param $media_type
     * @return string
     */
    private function _re_convert_media_type($media_type)
    {
        if (strlen($media_type)<1)
        {
            return 'std';
        }
        switch ($media_type)
        {
            //0:流畅,1:标清,2:高清,3:超清,9:4k(H265)
            case 2:
                $media_type = 'hd';
                break;
            case 1:
                $media_type = 'std';
                break;
            case 3:
                $media_type = 'sd';
                break;
            case 9:
                $media_type = '4k';
                break;
            case 0:
                $media_type = 'low';
                break;
            default:
                $media_type = 'std';
                break;
        }

        return $media_type;
    }
    /**
     * 融合报文 注入透传队列
     * @param $xml
     * @return array
     */
    private function fuse_execute($xml)
    {
        //解析xml文件信息
        $arr_obj = np_xml_to_array::parse2($xml);
        $this->asset_id = $arr_obj["content"]['assetid'];
        //组装pass_content内容
        $arr_pass_content = array(
            "msg_id" => $this->msg_id,
            "original_id" => trim($arr_obj["content"]["originalid"]),
            "main_tag" => trim($arr_obj["content"]["maintag"]),
            "new_cp_id" => $arr_obj['info']['fusionmarking']
        );
        //查询主媒资
        $check_result = $this->check_asset_existed($arr_pass_content['original_id']);
        if($check_result["ret"] == 0)
        {
            return array("ret"=>"1","reason"=>"主媒资已存在","data"=>array());
        }
        //pass_content内容信息转化为json数据格式
        $json_data = json_encode($arr_pass_content);

        //组装pass_queue需要的参数
        $add_pass_queue = array(
            "base_info"=>array(
                "nns_action"=>$arr_obj['operation'],
                "nns_type"=>4,
                "nns_message_id"=>$this->msg_id,
                "nns_cp_id"=>$this->source_id,
                "nns_status"=>1,
                "nns_content"=> $json_data,
            )
        );
        $re = $this->pass_queue_action('add', $add_pass_queue);
    }

    /**
     * 查询融合媒资是否已存在
     * @param string $import_id  媒资的原始ID （对应于nns_vod表中的nns_asset_import_id）
     * @return array('ret'=>'返回码','reason'=>'返回状态说明','data'=>array()返回的数据)
     */
    public function check_asset_existed($import_id)
    {
        $sql = "select nns_id from nns_vod where nns_asset_import_id = '{$import_id}'";
        $result = nl_query_by_db($sql, m_config::get_dc()->db());
        if(is_array($result))
        {
            return array("ret" => 0, "reason" => "媒资已存在", "data" => $result);
        }
        return array("ret" => 1, "reason" => "媒资不存在", "data" => array());
    }

    /**
     * 栏目同步 注入透传队列
     * @param $xml_arr
     * @return array
     */
    public function add_category_execute($xml_arr)
    {
        $action=$xml_arr['assetoperation'];
        $content = $xml_arr['content'];
        if($action == 1)
        {
            if(key_exists('1', $content))//多个栏目删除
            {
                foreach($content as $value) {
                    $category_info[] = array(
                        'category_id' => $value['columnid'],
                        'parent_category' => $value['parentid'],
                        'name' => $value['columnname'],
                        'sort' => intval($value['order']),
                        'display' => intval($value['display']),
                    );
                }
            }
            else
            {
                $category_info[] = array(
                    'category_id' => $content['columnid'],
                    'parent_category' => $content['parentid'],
                    'name' => $content['columnname'],
                    'sort' => intval($content['order']),
                    'display' => intval($content['display']),
                );
            }
        }
        elseif($action == 2)
        {
            if(key_exists('1', $content))//多个栏目删除
            {
                foreach ($content as $value)
                {
                    $category_info[] = $value['columnid'];
                }
            }
            else
            {
                $category_info[] = $content['columnid'];
            }
        }
        else
        {
            \nn_log::write_log_message(LOG_MODEL_ASSET_IMPORT, "操作类型错误请求action：" . var_export($action, true), $this->cp_id);
            return false;
        }

        $json_data = json_encode($category_info);
        //组装pass_queue需要的参数
        $add_pass_queue = array(
            "base_info"=>array(
                "nns_action"=>$action,
                "nns_type"=>0,
                "nns_message_id"=>$this->msg_id,
                "nns_cp_id"=>$this->source_id,
                "nns_status"=>1,
                "nns_content"=> $json_data,
            )
        );
        return $this->pass_queue_action('add', $add_pass_queue);
    }

    /**
     * @param $xml
     * 点播锁定解锁
     */
    public function lock_vod_execute($xml)
    {
        $obj = np_xml_to_array::parse2($xml);
        $datas = $obj['itemsdatas'];
        $content_producer = $obj['contentprovider'];
        $action=$obj['assetoperation'];
        foreach($datas as $value)
        {
            $vod_lock[] = array(
                'message_id' => $this->msg_id,
                'assets_id' => $value['originalid'],
                'cp_id' => $content_producer,
                'check' => $action,
                'assets_id_type' => 1,
            );
        }
        $action_bk = $action == '1' ? 7 : 6 ;
        $json_data = json_encode($vod_lock);
        //组装pass_queue需要的参数
        $add_pass_queue = array(
            "base_info"=>array(
                "nns_action"=>$action_bk,
                "nns_type"=>7,
                "nns_message_id"=>$this->msg_id,
                "nns_cp_id"=>$this->source_id,
                "nns_status"=>1,
                "nns_content"=> $json_data,
            )
        );
        return $this->pass_queue_action('add', $add_pass_queue);
    }

    /**
     * @param $obj
     * 频道锁定解锁
     * @return array
     */
    public function live_channel_lock_execute($obj)
    {
        $datas = $obj['itemsdatas'];
        $live_info = array();
        foreach($datas as $value)
        {
            $live_info[] = array(
                'message_id' => $this->msg_id,
                'channel_id' => $value['channelid'],
                'channel_name' => $value['channelname'],
                'status' => $value['status'],
            );
        }
        $action = $live_info[0]['status'] == '1' ? 7 : 6 ;
        $json_data = json_encode($live_info);
        //组装pass_queue需要的参数
        $add_pass_queue = array(
            "base_info"=>array(
                "nns_action"=>$action,
                "nns_type"=>99,
                "nns_message_id"=>$this->msg_id,
                "nns_cp_id"=>$this->source_id,
                "nns_status"=>1,
                "nns_content"=> $json_data,
            )
        );
        return $this->pass_queue_action('add', $add_pass_queue);
    }

    /**
     * 节目单同步
     * @param $obj
     * @return array
     */
    public function playbill_execute($obj)
    {
        $datas = $obj['itemsdatas'];
        //1添加修改 2删除
        $program_action = $obj['assetoperation'];
        $live_playbill_info = array();
        foreach($datas as $value)
        {
            $live_playbill_info[] = array(
                'message_id' => $this->msg_id,
                'program_action' => $program_action,
                'program_id' => $value['programid'],
                'program_name' => $value['programname'],
                'channel_id' => $value['channelid'],
                'channel_name' => $value['channelname'],
                'program_date' => $value['playdate'],
                'program_hourstart' => $value['playhourstart'],
                'program_hourend' => $value['playhourend'],
                'program_img_v' => $value['posterurl'],
            );
        }
        $action = $program_action == '1' ? 1 : 3 ;
        $json_data = json_encode($live_playbill_info);

        //组装pass_queue需要的参数
        $add_pass_queue = array(
            "base_info"=>array(
                "nns_action"=>$action,
                "nns_type"=>98,
                "nns_message_id"=>$this->msg_id,
                "nns_cp_id"=>$this->source_id,
                "nns_status"=>1,
                "nns_content"=> $json_data,
            )
        );
        return $this->pass_queue_action('add', $add_pass_queue);
    }

    public function status($message_id)
    {

    }

    /**
     * @description:播控注入cdn后统一反馈给二级
     * @author:xinxin.deng
     * @date: 2018/3/2 9:59
     * @param $message_id //消息id
     * @param $code //状态码，失败1，成功0
     * @param $reason //原因描述
     * @param $format //反馈格式
     * @param $arr_data //封装好了的反馈信息 array(
     *                                          'cdn_id' => ,注入cdn的id
     *                                          'site_id' => ,配置的站点id
     *                                          'mg_asset_type' => ,注入媒资类型
     *                                          'mg_asset_id' => ,主媒资的消息注入id
     *                                          'mg_part_id' => ,分集的消息注入id
     *                                          'mg_file_id' => ,片源的消息注入id,
     *                                          'is_finally' =>0, 0表示最终状态,反馈的时候将其unset掉
     *                                          );
     * @param $sp_id //sp配置信息
     */
    public function is_ok($message_id, $code, $reason, $arr_data, $sp_id, $format='xml')
    {
        $arr_sp_data = \m_config::_get_sp_info($sp_id);
        $sp_config = isset($arr_sp_data['data_info']['nns_config']) ? $arr_sp_data['data_info']['nns_config'] : array();
        //获取cp配置
        $arr_cp_data = \m_config::_get_cp_info(DEFAULT_SOURCE_ID);
        $cp_config = isset($arr_cp_data['data_info']['nns_config']) ? $arr_cp_data['data_info']['nns_config'] : array();
        unset($arr_data['is_finally']);//0标识未最终状态
        //兼容湖南电信二级消息反馈，1表示成功，0表示失败。
        $code = $code === 0 ? 1 : 0;
        $flag_message_feedback_enabled = (!isset($sp_config['message_feedback_enabled']) || $sp_config['message_feedback_enabled'] !=1) ? true : false;
        if(!$flag_message_feedback_enabled)
        {
            \m_config::write_callback_log('[' . date('Y-m-d H:i:s') . ']' . '不允许反馈或者反馈模式不正确：
            [message_feedback_enabled]=' . $sp_config['message_feedback_enabled'] . 'message_feedback_mode=' . $sp_config['message_feedback_mode'], DEFAULT_SOURCE_ID, $message_id);
            return;
        }
        //返回参数封装
        if ($format == 'json')
        {
            $arr_xml = array
            (
                'pushCode' => $message_id,
                'state' => $code,
                'feedbackContent' => urlencode($reason)
            );
            $xml = urldecode(json_encode($arr_xml));
            $data = 'cmsresult=' . $xml;

            $site_id = isset($cp_config['site_id']) ? $cp_config['site_id'] : '';
            $site_callback_url = isset($cp_config['site_callback_url']) ? $cp_config['site_callback_url'] : '';
        }
        else
        {
            $xml_info = array(
                'msgid' => $message_id,
                'state' => $code,
                'msg' => $reason,
                'info' => $arr_data,
            );
            $xml = self::_build_notify_xml($xml_info);
            $data = array(
                'cmsresult' => $xml,
            );
            $site_id = isset($sp_config['site_id']) ? $sp_config['site_id'] : '';
            $site_callback_url = isset($sp_config['site_callback_url']) ? $sp_config['site_callback_url'] : '';
        }

        //查询sp的上报地址/芒果使用站点ID
        if(!empty($site_id) && !empty($site_callback_url))
        {
            \m_config::write_callback_log('[' . date('Y-m-d H:i:s') . ']' . '站点反馈地址为:' . var_export($site_callback_url, true) . ',反馈
            数据为:' . $xml, DEFAULT_SOURCE_ID, $message_id);

            $http_curl = new np_http_curl_class();
            for ($i = 0; $i < 3; $i++) {
                //访问媒资注入接口
                $re = $http_curl->post($site_callback_url, $data, null, 2);
                $curl_info = $http_curl->curl_getinfo();
                $http_code = $curl_info['http_code'];
                \m_config::write_callback_log('[' . date('Y-m-d H:i:s') . ']' . '循环请求第' . $i . '次(如果请求返回post结果为true并且状态码不是200,就会默认循环3次,状态码为200,
                就跳出循环),' . '请求返回post结果为:' . $re . '请求返回状态为:' . var_export($http_code, true) . ',反回数据为:' . var_export($curl_info, true) . ',
                访问POST结果为:' . var_export($re, true), DEFAULT_SOURCE_ID, $message_id);

                if ($http_code != 200 && (int)$re === 1)
                {
                    continue;
                }
                else
                {
                    break;
                }
            }
        }
        return;
    }


    /**
     * @description:组装反馈的XML
     * @author:xinxin.deng
     * @date: 2018/2/26 14:25
     * @param $params
     * @return string|void
     */
    public function _build_notify_xml($params)
    {
        if(!is_array($params) || empty($params))
        {
            return ;
        }
        $dom = new DOMDocument('1.0', 'utf-8');
        $xmlresult = $dom->createElement('xmlresult');
        $dom->appendChild($xmlresult);
        foreach ($params as $key=>$value)
        {
            $$key = $dom->createElement($key);
            $xmlresult->appendchild($$key);
            if(!empty($value) && is_array($value))
            {
                foreach ($value as $k=>$val)
                {
                    $$k = $dom->createElement($k);
                    $$key->appendchild($$k);
                    //创建元素值
                    $content = $dom->createTextNode($val);
                    $$k->appendchild($content);
                }
            }
            else
            {
                //创建元素值
                $text = $dom->createTextNode($value);
                $$key->appendchild($text);
            }
        }
        return $dom->saveXML();
    }


    /**
     * 消息队列注入播控统一反馈给芒果二级，组装消息结构
     * @param int $state
     * @param string $reason
     * @param array $info
     */
    public function create_xml_respond_msg_to_csp($state=0, $reason='',$info=array())
    {

        $site_id = $this->arr_cp_config['data_info']['nns_config']['site_id'];
        $site_url = $this->arr_cp_config['data_info']['nns_config']['site_callback_url'];

        \m_config::write_callback_log('反馈到芒果二级地址信息：站点为-' . $site_id . ';站点地址为-' . $site_url, $this->source_id, $this->msg_id);
        //反馈状态转换
        $state = $state== 0 ?  1 : 0;
        if(!empty($site_id) && !empty($site_url))
        {
            $params = array(
                'msgid' => $this->msg_id,
                'state' => $state,
                'msg' => $reason
            );
            if(!empty($info))
            {
                $params['info'] = $info;
            }
            else
            {
                $params['info'] = array(
                    'cdn_id' => '',
                    'site_id' => $site_id,
                    'mg_asset_type' => $this->type,
                    'mg_asset_id' => $this->asset_id,
                    'mg_part_id' => $this->index_id,
                    'mg_file_id' => $this->media_id,
                );
            }
            $this->notify_msg($params, true, $site_url);
        }
        else
        {
            \m_config::write_callback_log('没有配置站点信息', $this->source_id, $this->msg_id);
        }
    }

    /**
     * 进行消息反馈
     * @param $params
     * @param bool $bool
     * @param string $site_url
     * @return array|string|void
     */
    public function notify_msg($params, $bool=false, $site_url='')
    {
        $http_curl = new np_http_curl_class();
        $xml = $this->_build_notify_xml($params);
        \m_config::write_callback_log('反馈给芒果二级的数据为：' . var_export($xml,true), $this->source_id, $this->msg_id);

        if(!$bool)//是否异步反馈通知上游
        {
            return $xml;
        }
        if(!empty($site_url))
        {
            $xml = array('cmsresult '=> $xml);
            $response = $http_curl->post($site_url, $xml, null, 2);
            $curl_info = $http_curl->curl_getinfo();
            \m_config::write_callback_log('芒果接收到反馈后响应的结果为：' . $response . ',POST反馈数据为：' . var_export($curl_info,true), $this->source_id, $this->msg_id);
        }
        else
        {
            \m_config::write_callback_log('没有配置反馈地址', $this->source_id, $this->media_id);
        }
    }

}